package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.config.exception.MyErrorException;
import com.crm.common.result.ResultCodeEnum;
import com.crm.dto.UserChangePasswordDto;
import com.crm.dto.UserSaveDto;
import com.crm.mapper.UserMapper;
import com.crm.model.User;
import com.crm.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @version 1.0
 * @description:
 * @date 2024/6/7 16:33
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveUser(UserSaveDto userSaveDto) {
        User userData = new User();
        BeanUtils.copyProperties(userSaveDto, userData);
        // 判断用户是否存在
        User userInfo = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userData.getUserName()));
        if (userInfo != null) {
            throw new MyErrorException(ResultCodeEnum.USER_IS_EXIST);
        }
        // 对密码处理
        userData.setPassword(DigestUtils.md5DigestAsHex(userData.getPassword().getBytes()));
        userData.setStatus(1);
        // 添加用户
        int res = userMapper.insert(userData);
        if (res == 0) {
            throw new MyErrorException(ResultCodeEnum.INSERT_FAIL);
        }

    }

    @Override
    public void changePassword(UserChangePasswordDto userChangePasswordDto) {
        // 判断用户是否存在
        User user = userMapper.selectById(userChangePasswordDto.getId());
        if (user ==null){
            throw new MyErrorException(ResultCodeEnum.USER_NOT_EXIST);
        }
        user.setPassword(DigestUtils.md5DigestAsHex(userChangePasswordDto.getPassword().getBytes()));
        int res = userMapper.updateById(user);
        if (res ==0){
            throw  new MyErrorException(ResultCodeEnum.UPDATE_FAIL);
        }
    }
}